from rest_framework import serializers
from .models import Product,HotRecommend,ProductBanners
class ProductBannersSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductBanners
        fields = ['image']

class ProductSerializer(serializers.ModelSerializer):
    images=serializers.SerializerMethodField()
    stock=serializers.SerializerMethodField()
    class Meta:
        model = Product
        fields = ["id","name","description","original_price","stock","category","cover","sold_quantity","discount_or_not","current_price","hot_recommend","images",'has_attr']
    def get_images(self, obj):
        # 获取商品的轮播图
        images=ProductBanners.objects.filter(product=obj)
        # 序列化
        images_list=ProductBannersSerializer(images,many=True)
        return images_list.data
    def get_stock(self, obj):
        sku_queryset=obj.sku_set.filter(stock__gt=0)
        total_stock=0
        for sku in sku_queryset:
            total_stock+=(sku.stock-sku.frozen_stock)
        return total_stock


class HotRecommendSerializer(serializers.ModelSerializer):
    products = serializers.SerializerMethodField()
    class Meta:
        model = HotRecommend
        fields = ['name','description','created_time',"products",'id','type']
    def get_products(self, obj):
        queryset=Product.objects.filter(hot_recommend__pid=obj.id)[:2]
        product_list_obj=ProductSerializer(queryset,many=True)
        return product_list_obj.data


from drf_haystack.serializers import HaystackSerializer
from .search_indexes import ProductIndex

class IndexSerializer(HaystackSerializer):
    object = ProductSerializer(read_only=True)  # 只读,不可以进行反序列化
    class Meta:
        index_classes = [ProductIndex]  # 索引类的名称
        fields = ('text', 'object')  # text 由索引类进行返回, object 由序列化类进行返回,第一个参数必须是text


